<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Express as LibraryExpress;
use app\common\library\Pay;
use app\common\model\Banner;
use app\common\model\Cart;
use app\common\model\Express;
use app\common\model\forest\Member;
use app\common\model\Goods;
use app\common\model\goods\Review;
use app\common\model\Order as ModelOrder;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\User;
use think\Db;
use think\Queue;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = ['*'];


    /**
     * 订单下单预览
     *
     */
    public function yuOrder()
    {
        $get = request()->get();
        $uid =  $this->auth->id;
        extract($get);
        if ($type == 'buyNow') {
            if (!isset($goods_ids) || empty($goods_ids)) {
                $this->error('参数错误');
            }
            if (!isset($num) || empty($num)) {
                $this->error('数量不能为空');
            }
            $data = Goods::get($goods_ids);
            if (!isset($data) || empty($data)) {
                $this->error('商品不存在');
            }
            if ($data->stock < $num) {
                $this->error('商品【' . $data->title . '】库存不足，不能下单');
            }
            if ($data->status == '0') {
                $this->error('商品【' . $data->title . '】已下架，不能下单');
            }
            if ($data->deletetime != null) {
                $this->error('商品【' . $data->title . '】已删除，不能下单');
            }
            $data['num'] = $num;
            $data['goods_id'] = $data['id'];
            $goods[] = ['num' => $num, 'money' => bcmul($data->price, $num, 2), 'original' => bcmul($data->original_price, $num, 2), 'goods_id' => $data['id'], 'goods' => $data->toArray()];
        } else {
            if (!isset($ids) || empty($ids)) {
                $this->error('参数错误');
            }
            $goods = Cart::getGoods($ids, $uid);
        }
        $order = new ModelOrder();
        $data = $order->yuOrder($goods, $pay_type ?? 0, $plant ?? 0, $address_id ?? 0, $uid);
        cache('order_' . $uid, $data, '900');
        $this->success('', $data);
    }
    /**
     * 订单统一下单
     *
     */
    public function addOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $uid = $this->auth->id;
        $data = cache('order_' . $uid);
        if (!$data) {
            $this->error('订单已失效，请重新选择商品');
        }
        extract($data);
        if (!isset($address_id) || empty($address_id)) {
            $this->error('收货地址不能为空');
        }
        if (!isset($pay_type)) {
            $this->error('请选择支付方式');
        }
        Db::startTrans();
        try {
            //添加订单商品信息
            $order = new ModelOrder();
            $order_id = $order->addData($data, $uid);
            if (!$order_id) {
                exception('下单失败');
            }
            $total_order = ModelOrder::get($order_id);
            $goods = OrderGoods::where('order_id', $order_id)->column('goods_id,goods_num');
            foreach ($goods as $key => $v) {
                Goods::reduceInventory($key, $v);
            }
            $list = $data['goodsList'];
            $goods_ids = array_column($list, 'id');
            Cart::delCart($uid, $goods_ids);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return self::error($e->getMessage() . $e->getLine());
        }
        Queue::later(900, 'app\common\job\Order', $total_order, 'order');
        cache('order_' . $uid, null);
        return $this->success('下单成功', $order_id);
    }

    /**
     * 立即付款
     *
     */
    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = ModelOrder::get($id);
        if ($order['status'] > '0') {
            $this->error('订单已支付');
        }
        try {
            if ($order['pay_money'] <= 0) {
                $res = $order->save(['status' => 1, 'paytime' => time()]);
                if (!$res)
                    exception('支付失败');
            } else {
                $data['title'] = '订单支付';
                $data['sn'] = $order['sn'];
                $data['pay_money'] = $order['pay_money'];
                if ($order['pay_type'] == '0') {
                    $sdk = Pay::wxpay($data, 'order');
                } elseif ($order['pay_type'] == '1') {
                    $sdk = Pay::alipay($data);
                } else if ($order['pay_type'] == '2') {
                    //余额支付
                    $sdk =  Pay::yue($data);
                }else{
                    $sdk = Pay::minipay($data, 'order');
                }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('支付成功', $sdk ?? '');
    }
    /**
     * 我的订单
     *
     */
    public function list()
    {

        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        //待付款
        if ($type == 1) {
            $where['status'] = ['=', '0'];
        }
        //待发货
        if ($type == 2) {
            $where['status'] = ['=', '1'];
        }
        //待收货
        if ($type == 3) {
            $where['status'] = ['=', '2'];
        }
        //待评价
        if ($type == 4) {
            $where['status'] = ['=', '3'];
        }
        //已完成
        if ($type == 5) {
            $where['status'] = ['=', '4'];
        }
        $where['user_id'] = ['=',  $this->auth->id];
        $order = ModelOrder::with(['goods'])->where($where)->where('status', '<>', '-1')->order('createtime desc')->paginate(10);
        $this->success('获取成功', $order);
    }
    /**
     * 订单详情
     *
     */
    public function info()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $info = ModelOrder::get($id, ['goods']);
        $this->success('获取成功', $info);
    }
    /**
     * 删除订单
     *
     */
    public function deleteOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }

        $res = ModelOrder::get($id);
        $res = $res->delete();
        if ($res) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
    /**
     * 取消订单
     *
     */
    public function cancelOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $res = ModelOrder::where('id', $id)->where('status', '0')->update(['status' => '-1', 'deletetime' => time()]);
        if ($res) {
            $this->success('取消成功');
        }
        $this->error('取消失败');
    }
    /**
     * 确认订单
     *
     */
    public function confirmOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $order = new ModelOrder;
            $order = $order->get($id);
            if (!$order) {
                exception('订单不存在');
            }
            if ($order->status != 2) {
                exception('订单状态错误');
            }
            $order->save(['status' => 3], ['id' => $id]);
            User::commission($order->pay_money, $order->sn, $this->auth->id);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error('操作失败：' . $th->getMessage());
        }
        $this->success('操作成功');
    }
    /**
     * 订单评论
     *
     */
    public function comment()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($goods_id) || empty($goods_id)) {
            $this->error('参数错误');
        }
        $Review = new Review();
        $res = $Review->addReview($post, $this->auth->id);
        if ($res === true) {
            $this->success('评论成功');
        }
        $this->error('评论失败:' . $res);
    }
    /**
     * 查看物流
     *
     */
    public function logistics()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = new ModelOrder();
        $order = $order->get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        $express = new LibraryExpress($order);
        $wuliu = $express->getOrderTracesByJson();
        $wuliu['express_name'] = Express::whereOr('customer', $order['express_com'])->value('name');
        $wuliu['address'] = $order['address'];
        $this->success('', $wuliu);
    }
}
